package io.nio;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * NIO demo 客户端
 *
 * @author verlet
 * @date 2020/2/29
 */
@Slf4j
public class Client {

    public static void main(String[] args) {
        //创建连接的地址
        InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8765);
        //声明连接通道
        SocketChannel sc = null;
        //建立缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in))) {
            //打开通道
            sc = SocketChannel.open();
            // 设置为不堵塞
            sc.configureBlocking(false);
            //进行连接
            if (!sc.connect(address)) {
                //连接不成功
                while (!sc.finishConnect()) {
                    log.info("因为连接需要时间,客户端不会阻塞，可以做其他工作");
                }
            }
            while (true) {
                //定义一个字节数组，然后使用系统录入功能：
                String msg = bufferedReader.readLine();
                //把数据放到缓冲区中
                buffer.put(msg.getBytes());
                //对缓冲区进行复位
                buffer.flip();
                //写出数据
                sc.write(buffer);
                //清空缓冲区数据
                buffer.clear();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sc != null) {
                try {
                    sc.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
